package org.zwt.common.formatter.impl;

import org.zwt.common.entity.HttpRequest;
import org.zwt.common.enumerate.HttpVersion;
import org.zwt.common.enumerate.RequestMethod;
import org.zwt.common.formatter.IRequestFormatter;

public class SimpleRequestFormatter implements IRequestFormatter {
    @Override
    public HttpRequest parse(String request) {
        HttpRequest httpRequest = new HttpRequest();
        try {
            /*
             * 1.获取请求体
             * */
            String[] headerAndBody = request.split("\r\n\r\n");
            if (headerAndBody.length >= 2) {
                httpRequest.setBody(new String(headerAndBody[1].getBytes(), "UTF-8"));
            }
            /*
             * 2.获取开始行,并拆解成该方法,url,版本
             * */
            String[] headers = headerAndBody[0].split("\r\n");
            String[] lines = headers[0].split(" ");
            if (lines.length >= 3) {
                httpRequest.setMethod(RequestMethod.valueOf(lines[0]));
                httpRequest.setOriginalUrl(lines[1]);
                httpRequest.setVersion(HttpVersion.fromText(lines[2]));

            }
            /*
             * 3.获取请求头
             * */
            if (headers.length >= 2) {
                for (int i = 1; i < headers.length; i++) {
                    String[] keyAndValue = headers[i].split(":");
                    if (keyAndValue.length >= 2) {
                        httpRequest.setHeader(keyAndValue[0], keyAndValue[1]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpRequest;
    }

    @Override
    public String format(HttpRequest request) {
        return "";
    }
}
